package main

import (
	"fmt"
	"githubproxy/basic"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

var logger = basic.XCLogger{}
var fileBasePath = "D:/abc/github.com"

func main() {
}

func init() {
	initAsync()
	http.HandleFunc("/", downloadHandler)
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		//log.Fatal(err)
		logger.ERROR(fmt.Sprintf("%v", err))
	}
}

func initAsync() {

}

func pathExists(path string) bool {
	_, err := os.Stat(path)
	return err == nil || os.IsExist(err)
}

func downloadHandler(w http.ResponseWriter, r *http.Request) {
	logger.Info(fmt.Sprintf("request uri: %v", r.RequestURI))
	localFile := fmt.Sprintf("%v%v", fileBasePath, r.RequestURI)
	localFilePath := localFile[0:strings.LastIndex(localFile, "/")]
	if pathExists(localFilePath) == false {
		os.MkdirAll(localFilePath, 0755)
	}
	if pathExists(localFile) {
		logger.Info(fmt.Sprintf("download %v from local", r.RequestURI))
		file, err := os.Open(localFile)
		defer file.Close()
		if err != nil {
			logger.ERROR(fmt.Sprintf("err:%v", err))
			http.Error(w, "传输文件失败", http.StatusInternalServerError)
		}
		w.Header().Set("Content-Disposition", "attachment; filename="+filepath.Base(file.Name()))
		fi, err := file.Stat()
		if err != nil {
			logger.ERROR(fmt.Sprintf("err:%v", err))
			http.Error(w, "传输文件失败", http.StatusInternalServerError)
		}
		w.Header().Set("Content-Length", strconv.FormatInt(fi.Size(), 10))
		w.Header().Set("Accept-Ranges", "bytes")
		w.Header().Set("content-type", "application/octet-stream")
		_, err = io.Copy(w, file)
		if err != nil {
			logger.ERROR(fmt.Sprintf("err:%v", err))
			http.Error(w, "传输文件失败", http.StatusInternalServerError)
		}
	} else {
		var url = fmt.Sprintf("%v%v", "https://github.com", r.RequestURI)
		resp, err := http.Get(url)
		defer resp.Body.Close()
		if err != nil {
			logger.ERROR(fmt.Sprintf("err:%v", err))
			http.Error(w, "传输文件失败", http.StatusInternalServerError)
		}

		filename := filepath.Base(r.RequestURI)
		w.Header().Set("Content-Disposition", "attachment; filename="+filename)
		w.Header().Set("Content-Type", resp.Header.Get("Content-Type"))
		w.Header().Set("Content-Length", resp.Header.Get("Content-Length"))
		w.Header().Set("Accept-Ranges", "bytes")
		_, err = io.Copy(w, resp.Body)
		if err != nil {
			logger.ERROR(fmt.Sprintf("err:%v", err))
			http.Error(w, "传输文件失败", http.StatusInternalServerError)
		}
	}
}
